#!/usr/bin/env python3
"""
任务调度系统启动脚本
支持优雅关闭和信号处理
"""

import asyncio
import signal
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from loguru import logger
import uvicorn
from app.config.settings import settings, validate_settings


def setup_logging():
    """设置日志配置"""
    logger.remove()  # 移除默认处理器

    # 添加控制台处理器
    logger.add(
        sys.stderr,
        level=settings.log_level,
        format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
    )

    # 添加文件处理器（如果配置了）
    if settings.log_file:
        log_path = Path(settings.log_file)
        log_path.parent.mkdir(parents=True, exist_ok=True)

        logger.add(
            settings.log_file,
            level=settings.log_level,
            rotation=settings.log_rotation,
            retention=settings.log_retention,
            compression="zip",
            format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
        )


class GracefulKiller:
    """优雅关闭处理器"""

    def __init__(self):
        self.kill_now = False
        signal.signal(signal.SIGINT, self._handle_signal)
        signal.signal(signal.SIGTERM, self._handle_signal)

        # Windows特定信号
        if hasattr(signal, "SIGBREAK"):
            signal.signal(signal.SIGBREAK, self._handle_signal)

    def _handle_signal(self, signum, frame):
        logger.info(f"收到关闭信号 {signum}")
        self.kill_now = True


async def run_server():
    """运行服务器"""
    # 验证配置
    validate_settings()

    # 设置日志
    setup_logging()

    # 创建优雅关闭处理器
    killer = GracefulKiller()

    logger.info("正在启动任务调度系统...")
    logger.info(f"服务器地址: http://{settings.host}:{settings.port}")
    logger.info(f"调试模式: {settings.debug}")

    # 配置uvicorn
    config = uvicorn.Config(
        "main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
        log_level=settings.log_level.lower(),
        access_log=False,  # 使用自定义日志
    )

    server = uvicorn.Server(config)

    try:
        # 启动服务器
        await server.serve()
    except KeyboardInterrupt:
        logger.info("收到键盘中断")
    except Exception as e:
        logger.error(f"服务器运行错误: {e}")
        raise
    finally:
        logger.info("服务器已停止")


def main():
    """主函数"""
    try:
        asyncio.run(run_server())
    except KeyboardInterrupt:
        logger.info("程序被用户中断")
    except Exception as e:
        logger.error(f"程序运行错误: {e}")
        sys.exit(1)
    finally:
        logger.info("程序退出")


if __name__ == "__main__":
    main()
